package system

import (
	"cubeAdmin/common/jwtauth"
	"cubeAdmin/controllers"
	"cubeAdmin/models"
	"cubeAdmin/vo"
	"encoding/json"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/core/validation"
)

// JobController 岗位api
type JobController struct {
	controllers.BaseController
}

func (c *JobController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// Index 获取部门列表视图
// @router /index [get]
func (c *JobController) Index() {
	c.Data["pageTitle"] = "岗位列表"
	user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
	c.Data["user"] = user
	c.TplName = "system/dept/main.tpl"
}

// GetAll ...
// @Title 岗位列表
// @Description 岗位列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *JobController) GetAll() {
	enabled, _ := c.GetInt64("enabled", -1)
	total, list := models.GetAllJob(c.GetParams(), enabled)
	c.Ok(vo.ResultList{Content: list, TotalElements: total})
}

// DTree 获取部门树
// @router /tree [post]
func (c *JobController) DTree() {
	list := models.GetAllJobList()
	c.DataTree(list)
}

// Post ...
// @Title 岗位添加
// @Description 岗位添加
// @Success 200 {object} controllers.Result
// @router / [post]
func (c *JobController) Post() {
	var model models.SysJob
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, 5001)
		}
	}
	_, e := models.AddJob(&model)
	if e != nil {
		c.Fail(e.Error(), 5002)
	}
	c.Ok("操作成功")
}

// Put ...
// @Title 岗位修改
// @Description 岗位修改
// @Success 200 {object} controllers.Result
// @router / [put]
func (c *JobController) Put() {
	var model models.SysJob
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, 5003)
		}
	}
	e := models.UpdateByJob(&model)
	if e != nil {
		c.Fail(e.Error(), 5004)
	}
	c.Ok("操作成功")
}

// Delete ...
// @Title 岗位删除
// @Description 岗位删除
// @Success 200 {object} controllers.Result
// @router / [delete]
func (c *JobController) Delete() {
	var ids []int64
	json.Unmarshal(c.Ctx.Input.RequestBody, &ids)
	logs.Info(ids)
	e := models.DelByJob(ids)
	if e != nil {
		c.Fail(e.Error(), 5005)
	}
	c.Ok("操作成功")
}
